package com.ddone.demo.handler;

import lombok.extern.slf4j.Slf4j;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ddone
 * @date 2024/3/23-19:27
 *
 * 异常处理的Handler 是根据异常类型 来匹配handler方法
 * 注解只有一个不需要扫描, @Configuration
 */
@ControllerAdvice
// @RestControllerAdvice = @ResponseBody @ControllerAdvice
@Slf4j
public class DemoExceptionHandler {

    @ExceptionHandler(value = ArithmeticException.class)
    public String test1(Exception e, Model model, HttpServletRequest request){
        log.error("程序报错了");
        model.addAttribute("exception", e);
        return "error";
    }

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Map<String,Object> test2(Exception e){
        log.error("出现异常了");
        return new HashMap<String,Object>(){{
            put("code", "005");
            put("msg", e.getMessage());
        }};
    }
}
